import React, {Component} from 'react'

import {View} from '@tarojs/components'
import {AtIcon} from "taro-ui";
import {getLike, getDisLike} from '../../../service/like'
import './index.scss'

type PageStateProps = {
  uID: any //用户id
  Data: any //dy——like
}

type PageDispatchProps = {}

type PageOwnProps = {}

type PageState = {
  isShow: boolean
  LikeList: number[]
  userID: string
}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Like {
  props: IProps;
}

class Like extends Component<IProps, PageState> {
  constructor(props) {
    super(props);
    this.state = {
      isShow: false,
      userID: '',
      LikeList: []
    }
  }

  componentDidMount() {
    // console.log(this.props);
    this.loadData()
  }

  loadData = () => {
    const {LikeList} = this.state
    const {Data, uID} = this.props
    if(Data){
      Data.dy_like.map((item: any) => {
        return LikeList.push(Number(item.user_id))
      })
      // console.log(LikeList);
      this.setState({
        LikeList: LikeList,
        userID: uID
      })
      let res = LikeList.indexOf(uID)
      if (res === -1) {
        this.setState({
          isShow: false
        })
      } else {
        this.setState({
          isShow: true
        })
      }
    }
  }

  handleClickChangeFabState = async () => {
    const {LikeList,userID} = this.state
    const {Data} = this.props
    const res = LikeList.indexOf(Number(userID))
    if (res === -1) {
      // this.state.commentList[item].dy_like.push(uName)
      LikeList.push(Number(userID))
      this.setState({
        LikeList: LikeList,
        isShow: true
      })
      await getLike({
        dy_id: Data.id,
        user_id: userID
      })
      console.log(`对 ${Data.id} 进行了点赞`)
    } else {
      // this.state.commentList[item].dy_like.splice(res, 1)
      LikeList.splice(res, 1)
      this.setState({
        LikeList: LikeList,
        isShow: false
      })
      await getDisLike({
        dy_id: Data.id,
        user_id: userID
      })
      console.log(`对 ${Data.id} 进行了取消点赞`)
    }
  }

  render() {
    const {isShow, LikeList} = this.state
    return (
      <View className='tabItem_icon_item' onClick={this.handleClickChangeFabState}>
        <View className='tabItem_center'>
          {
            isShow ? <AtIcon value='heart-2' size='18' color='#e33e33' /> :
              <AtIcon value='heart' size='18' color='#333' />
          }
          <View className='tabItem_icon_text'>{LikeList.length}</View>
        </View>
      </View>
    )
  }
}


export default Like
